//
//  RecordListDAO.m
//  ImGuider
//
//  Created by 王鹏宇 on 2017/10/17.
//  Copyright © 2017年 AudioCtrip. All rights reserved.
//

#import "RecordListDAO.h"
#import "DBHelper.h"


#define TABLE_NAME @"record_list"

#define ID      @"_id" // 本地数据库 播放记录 url
#define URL     @"URL"
#define SPARE   @"spare"


@implementation RecordListDAO


+ (BOOL)createMetadataTabWithDB:(FMDatabase *)db {
    
    NSString *sqlStr = [NSString stringWithFormat:@"create table %@(%@ integer not null primary key autoincrement,%@ text, %@ text)",TABLE_NAME,ID,URL,SPARE];
    BOOL success = [db executeUpdate:sqlStr];
    
    return success;
}

+ (void)insertPlayRecord:(NSString *)playPath success:(BOOL *)success {
    
    
    
    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
    
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        if ([db open]) {
            
            if (![db tableExists:TABLE_NAME]) {
                
                [self createMetadataTabWithDB:db];
            }
            
            NSString *sql = [NSString stringWithFormat:@"select * from %@ where %@ = ?",TABLE_NAME,URL];
            FMResultSet *set = [db executeQuery:sql,playPath];
            if ([set next]) {
                
                [set close];
                return ;
            }else {
                
                NSString *sql2 = [NSString stringWithFormat:@"insert into %@(%@) values (?)",TABLE_NAME,URL];
                *success = [db executeUpdate:sql2,playPath];
            }
            
            if (!success) {
                IGLog(@"----------------数据库插入错误-------------");
                *rollback = YES;
                return;
            }
        }
    }];
}

+ (void)QueryRecordPlayPath:(NSString *)playPath  Block:(void (^)(BOOL))block{
    
    
    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
    
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        if ([db open]) {
            
            if (![db tableExists:TABLE_NAME]) {
                [self createMetadataTabWithDB:db];
                return;
            }
            
            
            NSString *sql = [NSString stringWithFormat:@"select * from %@ where %@ = ?",TABLE_NAME,URL];
            FMResultSet *set = [db executeQuery:sql,playPath];
            
            BOOL isContain = false;
            if ([set next]) {
                
                isContain = true;
            }
            if (block) {
                block(isContain);
            }
            
        }
    }];
}

@end

